/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package restauranteaplicacion.Modificaciones;
import Clases.jcThread;
import entidad.Orden;
import entidad.Detalleorden;
import CapaNegocios.CNOrden;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import Clases.OrdenesCocinaLista;
import java.awt.Color;
import controlrestaurante.pmf;
import java.awt.Cursor;

/**
 *
 * @author a
 */
public class OrdecCocina extends javax.swing.JFrame implements Runnable{

    /**
     * Creates new form OrdecCocina
     */
    List<Object> listaObjectos;
    List<OrdenesCocinaLista> listado;
    Thread hilo;
    int next=0;
    public static int  numeroSalida ; 
    private static boolean bandera;
    private boolean primeraVes=true;
    private boolean pausa;
   public OrdecCocina() {
        initComponents();
        this.setCursor(Cursor.WAIT_CURSOR);
        jcThread.iniciarHilo(jProgressBar1, 100);
        hilo=new Thread(this);
        /*listaObjectos = new ArrayList<Object>();      
        jPanel3.setLayout(new GridLayout(2,4));
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        for (int x = 0 ;x<=11;x++)
            jPanel3.add(new JPanel(new GridLayout(1,1)));
        listado= new ArrayList<OrdenesCocinaLista>();
        //jPanel3.setSize(243, 150);
        //AgregarOrdenes();
        numeroSalida = -1;
        bandera= true;
        /*if(OrdenesCocinaLista.agregarOrdenes(CNOrden.buscarActivos(), listado))
        {
            actualizarPanel();      
        }*/
        hilo.start();
        //pausa=false;
        this.setCursor(Cursor.DEFAULT_CURSOR);
    }
    //funcion en prueba
    private void AgregarNuevasOrdenes()
    {
        try{
            listaObjectos.clear();
            if(listado!=null)
            {
                for(OrdenesCocinaLista tempOrdenes : listado )
                {
                    String mensaje = tempOrdenes.getComanda();
                    JLabel temp = new javax.swing.JLabel(mensaje);
                    temp.setOpaque(true);
                    temp.setBackground(Color.WHITE);
                    int x = (int)numeroSpiner.getValue();
                    temp.setFont(new java.awt.Font("Arial", 0, x));
                    //temp.setLineWrap(true); 
                    //temp.setEditable(false);
                    temp.addMouseListener(new MouseAdapter() {
                         @Override
                         public void mouseClicked(MouseEvent mouseEvent) {
                             if (mouseEvent.getClickCount() >= 1) {
                                JLabel temp = (JLabel) mouseEvent.getSource();
                                int num = Integer.valueOf(temp.getName()).intValue();
                                salida(num);
                                actualizarPanel();     
                            }
                         }
                    });
                    temp.setName(String.valueOf(tempOrdenes.getIdOrden()));
                    JScrollPane scroll = new JScrollPane(); 
                    scroll.setViewportView(temp);
                    listaObjectos.add(scroll);
                }
                dibujarOrdenes(listaObjectos);
            }
        }
        catch(Exception e)
        {};
    }
     //funcion actualmente
    private void AgregarOrdenes()
    {
        listaObjectos.clear();
        List<Orden> lista = CNOrden.buscarActivos();
        if(lista != null)
        {
            for(Orden or : lista)
            {
                String texto="Mesa:"+or.getMesaidMesa().getNumeroMesa()+"\n";
                //boolean ban=true;
                for(Detalleorden det : or.getDetalleordenCollection())
                {
                    if(det.getPlatosidPlatos()!=null)
                    texto = texto + String.valueOf(det.getCantidad())+ "    "
                            +det.getPlatosidPlatos().getNombre()+" "+det.getDescripcion()
                            +"\n";
                    //ban=false;
                }
                //if(ban)
                //{
                //    AgregarOrdenes();
                //    return;
                //}
                JTextArea temp = new JTextArea(texto);
                temp.setLineWrap(true); 
                temp.setEditable(false);
                temp.addMouseListener(new MouseAdapter() {
                     @Override
                     public void mouseClicked(MouseEvent mouseEvent) {
                         if (mouseEvent.getClickCount() >= 1) {
                            JTextArea temp = (JTextArea) mouseEvent.getSource();
                            int num = Integer.valueOf(temp.getName()).intValue();
                            salida(num);
                            if(OrdenesCocinaLista.agregarOrdenes(CNOrden.buscarActivos(), listado))
                            {
                                actualizarPanel();      
                            }
                        }
                     }
                });
                temp.setName(String.valueOf(or.getIdOrden()));
                JScrollPane scroll = new JScrollPane(); 
                scroll.setViewportView(temp);
                listaObjectos.add(scroll);
            }
            dibujarOrdenes(listaObjectos);
        }
    }
    
    private void salida(int x)
    {
        try
        {
            jcThread.iniciarHilo(jProgressBar1, 100);
            if(listado.isEmpty())
                return;
            if(x == -1)
                return;
            numeroSalida = x;
             bandera = false; 
            this.setCursor(Cursor.WAIT_CURSOR);
            while(pausa)
            {
                
            }
            CNOrden.salidaCocina(x);
            for(OrdenesCocinaLista temp : listado)
            {
                if(temp.getIdOrden() == x)
                {
                    listado.remove(temp);
                }
            }              
            numeroSalida = -1;
            bandera = true;
            this.setCursor(Cursor.DEFAULT_CURSOR);
            jcThread.finalizarHilo();
        }
        catch(Exception e){
            this.setCursor(Cursor.DEFAULT_CURSOR);
            bandera = true;
            jcThread.finalizarHilo();
        }
        
        
    }
    
    private void nextNumero()
    {
        if(listaObjectos.size()>12)
            next=+1;
        else 
            next=0;
    }
    private void beforeNumero()
    {
        if(listaObjectos.size()>12)
            next=-1;
    }
    
    private void dibujarOrdenes(List<Object> listaob)
    {
        try{
            int y = next;
            for(Component x :this.jPanel3.getComponents())
            {
                JPanel temp=null;
                temp= (JPanel)x;
                if(temp!=null)
                    if(y< listaob.size())
                    {
                        temp.add((Component)listaob.get(y));
                    }
                y++;
            }
        }
        catch(Exception e)
        {}
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel6 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        numeroSpiner = new javax.swing.JSpinner();
        jProgressBar1 = new javax.swing.JProgressBar();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel3 = new javax.swing.JPanel();

        javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
        jPanel6.setLayout(jPanel6Layout);
        jPanel6Layout.setHorizontalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel6Layout.setVerticalGroup(
            jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(851, 489));
        getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS));

        jPanel1.setBackground(new java.awt.Color(54, 149, 240));
        jPanel1.setMaximumSize(new java.awt.Dimension(32767, 70));
        jPanel1.setMinimumSize(new java.awt.Dimension(0, 70));
        jPanel1.setPreferredSize(new java.awt.Dimension(795, 70));

        jButton1.setBackground(new java.awt.Color(255, 255, 255));
        jButton1.setForeground(new java.awt.Color(102, 102, 255));
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/reload-3x.png"))); // NOI18N
        jButton1.setText("Actualizar");
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("Orden de Cocina de Platillos");

        numeroSpiner.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        numeroSpiner.setValue(14);
        numeroSpiner.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                numeroSpinerStateChanged(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addComponent(jButton1)
                .addGap(33, 33, 33)
                .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addGap(58, 58, 58)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49)
                .addComponent(numeroSpiner, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(23, 23, 23))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(numeroSpiner)
                    .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        getContentPane().add(jPanel1);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new java.awt.GridLayout(1, 0));

        jPanel3.setLayout(new java.awt.GridLayout(2, 4));
        jScrollPane1.setViewportView(jPanel3);

        jPanel2.add(jScrollPane1);

        getContentPane().add(jPanel2);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
         jcThread.iniciarHilo(jProgressBar1, 100);
        if(OrdenesCocinaLista.agregarOrdenes(CNOrden.buscarActivos(), listado))
        {
            actualizarPanel();      
        }
        jcThread.finalizarHilo();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void numeroSpinerStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_numeroSpinerStateChanged
        // TODO add your handling code here:
         actualizarPanel(); 
    }//GEN-LAST:event_numeroSpinerStateChanged

    private void actualizarPanel()
    {
        try{
        jPanel3.removeAll();
        for (int x = 0 ;x<=11;x++)
            jPanel3.add(new JPanel(new GridLayout(1,1)));
        //AgregarOrdenes();
        AgregarNuevasOrdenes();
        jPanel3.updateUI();
        }
        catch(Exception e){}
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OrdecCocina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OrdecCocina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OrdecCocina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OrdecCocina.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OrdecCocina().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner numeroSpiner;
    // End of variables declaration//GEN-END:variables

    @Override
    public void run() {
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        Thread ct = Thread.currentThread();
        if(primeraVes)
        {
            listaObjectos = new ArrayList<Object>();      
            jPanel3.setLayout(new GridLayout(2,4));
            this.setExtendedState(JFrame.MAXIMIZED_BOTH);
            for (int x = 0 ;x<=11;x++)
                jPanel3.add(new JPanel(new GridLayout(1,1)));
            listado= new ArrayList<OrdenesCocinaLista>();
            //jPanel3.setSize(243, 150);
            //AgregarOrdenes();
            numeroSalida = -1;
            bandera= true;
            pausa= false;
            primeraVes=false;
           
        }
        while(ct==hilo)
        {
            try {
                if(bandera)
                {
                    pausa=true;
                    //pmf.getInstancia().cerrarEMF();
                    if(OrdenesCocinaLista.agregarOrdenes(CNOrden.buscarActivos(), listado))
                    {
                        actualizarPanel();      
                    }
                    pausa=false;
                    jcThread.finalizarHilo();
                }             
               
            }
             catch(Exception e){
                 pausa=false;
             };
             try{
              hilo.sleep( 5000 );
             }
             catch(Exception e){};
            
        }
    }
}
